package com.onlineclass.userserver.controller;

import com.onlineclass.beas.ResultObject;
import com.onlineclass.beas.User;
import com.onlineclass.beas.UserInfo;
import com.onlineclass.userserver.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {

    @Autowired
    IUserService service;

    @Autowired
    private RedisTemplate redisTemplate;

    private  User getUser(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        String token = "";
        for (Cookie cookie : cookies) {
            if ("token".equals(cookie.getName())){
                token = cookie.getValue();
            }
        }
        return  (User) redisTemplate.opsForValue().get(token);
    }


    @RequestMapping("/login")
    public User login(@RequestBody User user){
        log.info(String.valueOf(user));
        User u = service.login(user);
        log.info(String.valueOf(u));
        return u;
    }

    @RequestMapping("/selectUserInfo")
    public ResultObject selectUserInfo(HttpServletRequest request){
        UserInfo userInfo = service.selectUserInfo(getUser(request));
        if (userInfo != null) {
            return new ResultObject(1,"",userInfo);
        } else {
            return new ResultObject(0,"查询不成功","");
        }

    }



}
